<template>
  <div class="layout">
    <div class="banner">
      <div
        class="txt wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <img class="dao1" src="@/assets/img/home/dao1.png" alt="" />
        <h3 class="font2">{{ $t("HELPME") }}</h3>
      </div>
      <!-- <div class="bgs"></div> -->
    </div>

    <div
      class="pic wow fadeInUp u-f-ajc"
      data-wow-delay="0.3s"
      data-wow-duration="1s"
    >
      <img class="home1" src="@/assets/img/home/home1.png" alt="" />
    </div>

    <div class="page1">
      <div
        class="self-introduction wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <div class="introduction">
          {{ $t("mynames") }}
        </div>
        <div class="u-f-ac u-f-ajc">
          <img
            class="icon1 cp"
            @click="openUrl('https://twitter.com/DaiSolana')"
            src="@/assets/img/home/images-1.png"
            alt=""
          />
          <img class="icon1 cp" src="@/assets/img/home/unnamed.png" @click="openUrl('https://dexscreener.com/solana/a4kmzjeb6hn6kuuymvn9421cqz2k7gfd2fhxnn1jtqbj')" alt="" />
          <img class="icon1 cp" src="@/assets/img/home/images-2.png" @click="openUrl('https://t.me/+NMkdsLWfnEIyNDk0')" alt="" />
        </div>
      </div>

      <div
        class="buy-dai u-f-ajc u-f-column wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <!-- <img class="button1 cp" src="@/assets/img/home/button1.png" alt="" /> -->
        <!-- <img class="button1 cp" src="@/assets/img/home/button2.png" alt="" /> -->
        <img
          class="button1 cp"
          @click="
            openUrl(
              'https://raydium.io/swap/?inputCurrency=2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk&outputCurrency=4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R&inputAmount=1.821557862&outputAmount=0.000811&fixed=in'
            )
          "
          src="@/assets/img/home/button1-active.png"
          alt=""
        />
        <img
          class="button1 cp"
          @click="openUrl('https://jup.ag/swap/SOL-2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk')"
          src="@/assets/img/home/button2-active.png"
          alt=""
        />
        <div class="POWERED">{{ $t("POWEREDBY") }}</div>
        <div class="u-f-ajc cp mobile-none" @click="copyText('2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk')">
          <img class="copy" src="@/assets/img/home/copy-left.webp" alt="" />
          <div class="CA">ca:2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk</div>
          <img class="copy" src="@/assets/img/home/copy.png" alt="" />
        </div>
        <div
          class="u-f-ajc cp u-f-column pc-none"
          @click="copyText('2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk')"
        >
          <div class="CA2">ca:2T56xDvq5GU3JKPF3qwmEJpCyDhiX7dvjbs4QQwZAQvk</div>
          <div class="u-f-ajc">
            <img class="copy" src="@/assets/img/home/copy-left.webp" alt="" />
            <img class="copy" src="@/assets/img/home/copy.png" alt="" />
          </div>
        </div>
      </div>

      <div
        class="u-f-ajc u-f-column tokenomics-box wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <!-- <div class="tokenomics">TOKENOMICS</div> -->
        <img class="dao3" src="@/assets/img/home/dao2.png" alt="" />
        <img class="home2" src="@/assets/img/home/home2.png" alt="" />
        <div class="u-f-ac u-f-jsb" style="width: 100%">
          <img class="home3" src="@/assets/img/home/home3.png" alt="" />
          <img class="home3" src="@/assets/img/home/home3-2.png" alt="" />
        </div>
      </div>

      <div
        class="u-f-ajc u-f-column tokenomics-box wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <!-- <div class="tokenomics">$DAI MEMES</div> -->
        <img class="dao3" src="@/assets/img/home/dao3.png" alt="" />

        <swiper class="swiper mobile-none" :options="swiperOption">
          <swiper-slide v-for="(item, index) in imgList" :key="index"
            ><img class="swiper-img" :src="item.img" alt=""
          /></swiper-slide>
        </swiper>

        <div class="pc-none">
          <img class="home2 home4" src="@/assets/img/home/home4.png" alt="" />
          <img class="home2 home4" src="@/assets/img/home/home4-2.png" alt="" />
          <img class="home2 home4" src="@/assets/img/home/home4-3.png" alt="" />
          <img class="home2 home4" src="@/assets/img/home/home4-4.png" alt="" />
          <img class="home2 home4" src="@/assets/img/home/home4-5.png" alt="" />
          <img class="home2 home4" src="@/assets/img/home/home4-6.png" alt="" />
          <video
            class="home4 video"
            src="@/assets/img/home/home4-7.mp4"
            autoplay
            controls
            crossorigin
            loop
          ></video>
        </div>
      </div>

      <div
        class="u-f-ajc u-f-column tokenomics-box tokenomics-box2 wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <!-- <div class="tokenomics">$LONG LIVE CHART</div> -->
        <img class="dao4" src="@/assets/img/home/dao4.png" alt="" />
        <img class="home2 cp" src="@/assets/img/home/home5.png" alt="" />
        <!-- @click="
            openUrl(
              'https://dexscreener.com/solana/46cchbjxwpxhds1tur37pkymhhuetx1qi656pcrbfrty'
            )
          " -->
        <!-- <iframe
          src="https://dexscreener.com/solana/46cchbjxwpxhds1tur37pkymhhuetx1qi656pcrbfrty"
          width="100%"
          height="600"
          frameborder="0"
          allowfullscreen
        ></iframe> -->
      </div>

      <div
        class="u-f-ajc u-f-column COPYRIGHT-box wow fadeInUp"
        data-wow-delay="0.3s"
        data-wow-duration="1s"
      >
        <img class="home6" src="@/assets/img/home/home6.png" alt="" />
        <div class="POWERED2 COPYRIGHT">{{ $t("COPYRIGHT") }}</div>
        <div class="POWERED2 COPYRIGHT">{{ $t("DOOBEE") }}</div>
      </div>
    </div>

    <van-popup v-model="showPopup" position="top" :style="{ height: '35%' }">
      <div class="popup-box u-f-ajc u-f-column">
        <div class="tab-item cp" @click="goAnchor('#AIComputing')">
          {{ $t("AIComputing") }}
        </div>
        <div class="tab-item cp" @click="goAnchor('#Distributed-storage')">
          {{ $t("DistributedStorage") }}
        </div>
        <div class="tab-item cp" @click="goAnchor('#Learn')">
          {{ $t("Learn") }}
        </div>
        <!-- Connect Wallet -->
        <div
          class="connect-wallet u-f-ajc cp"
          @click="showLogin = true"
          v-if="!walletAddress"
        >
          <img src="@/assets/img/home/connect.png" alt="Connect Wallet" />
          <div class="f-w-700">{{ $t("ConnectWallet") }}</div>
        </div>
        <!-- logining~ -->
        <div v-else class="u-f-ajc logout cp" @click="goAccount">
          <img
            src="@/assets/img/home/avatar.png"
            alt="walletAddress"
            style="margin-right: 10px"
          />
          <div class="text-overflow">{{ replaceMiddleWithEllipsis }}</div>
        </div>
      </div>
    </van-popup>

    <van-popup
      v-model="showLogin"
      position="center"
      closeable
      class="login-popup"
    >
      <div class="popup-box u-f-ajc u-f-column">
        <!-- <div class="connect-wallet u-f-ajc cp" @click="connectOkxWallet">
          <img src="@/assets/img/home/OKX.png" alt="OKX" />
          <div class="f-w-700">OKX</div>
        </div> -->
        <!-- <w3m-button /> -->
        <div
          class="connect-wallet connect-wallet2 u-f-ajc cp"
          @click="connectWalletConnect"
        >
          <img src="@/assets/img/home/Wallet.png" alt="walletConnect" />
          <div class="f-w-700">walletConnect</div>
        </div>
      </div>
    </van-popup>

    <van-popup
      v-model="showForm"
      position="center"
      round
      closeable
      class="form-popup"
    >
      <div class="u-f-ac u-f-column">
        <div class="form-title f-w-700">{{ $t("RegisterInformation") }}</div>
        <!-- <div class="form-item">
          <div class="u-f-ac input-title">
            <img src="@/assets/img/home//nicheng.png" />
            <div>{{ $t("nickname") }}</div>
          </div>
          <div class="inputs u-f-ac">
            <input
              type="text"
              v-model="registerForm.nickname"
              :placeholder="$t('nicknamePla')"
            />
          </div>
        </div> -->
        <div class="form-item">
          <div class="u-f-ac input-title">
            <img src="@/assets/img/home/shoujihao.png" />
            <div>{{ $t("inviteCode") }}</div>
          </div>
          <div class="inputs u-f-ac">
            <input
              type="text"
              v-model="registerForm.code"
              maxlength="6"
              :placeholder="$t('inviteCodePla')"
            />
          </div>
        </div>
        <!-- <div class="form-item">
          <div class="u-f-ac input-title">
            <img src="@/assets/img/home/youxiang.png" />
            <div>{{ $t("Email") }}</div>
          </div>
          <div class="inputs u-f-ac">
            <input
              type="text"
              v-model="registerForm.email"
              :placeholder="$t('EmailPla')"
            />
          </div>
        </div> -->
        <div class="form-item">
          <div class="u-f-ac input-title">
            <img src="@/assets/img/home/nicheng.png" />
            <div>{{ $t("walletAddress") }}{{ $t("walletAddressMsg") }}</div>
          </div>
          <div class="inputs u-f-ac">
            <input
              type="text"
              v-model="registerForm.address"
              disabled
              :placeholder="$t('walletAddressPla')"
            />
          </div>
        </div>
        <div class="submit-button f-w-700 u-f-ajc cp" @click="submit">
          {{ $t("submit") }}
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import WOW from "wowjs";
// import script from "@/assets/js/script.js";

let timer;
import { addressLogin, addressRegister } from "@/api/home";
import {
  watchAccount,
  disconnect,
  getAccount,
  fetchBalance,
  signMessage,
} from "@wagmi/core";
import {
  useWeb3Modal,
  useWeb3ModalState,
  useWeb3ModalEvents,
} from "@web3modal/wagmi1/vue";
// const state = useWeb3ModalState();
// const events = useWeb3ModalEvents();

import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import "swiper/css/swiper.css";

export default {
  name: "Home",
  data() {
    return {
      showPopup: false,
      showLogin: false,
      walletAddress: "",
      language: localStorage.getItem("lang") || "en",
      showForm: false,
      isRegister: false,
      registerForm: {
        address: "",
        code: "",
        // email: "",
        // nickname: "",
      },
      imgList: [
        {
          img: require("@/assets/img/home/home4.png"),
        },
        {
          img: require("@/assets/img/home/home4-2.png"),
        },
        {
          img: require("@/assets/img/home/home4-3.png"),
        },
        {
          img: require("@/assets/img/home/home4-4.png"),
        },
        {
          img: require("@/assets/img/home/home4-5.png"),
        },
        {
          img: require("@/assets/img/home/home4-6.png"),
        },
      ],

      swiperOption: {
        // width: undefined,
        // //设置断点宽度
        // breakpoints: {
        //   1024: {
        //     width: 500,
        //   },
        //   768: {
        //     width: undefined, //取消width，恢复自适应
        //   },
        // },
        // autoHeight: true, //高度随内容变化
        autoplay: true,
        mousewheel: true, //开启鼠标滚轮控制Swiper切换
        slidesPerView: 6, // 容器同时显示的数量
        spaceBetween: 100, // 在slide之间设置距离
        slidesPerGroup: 1, // 在carousel mode下定义slides的数量多少为一组
        loop: true,
        loopAdditionalSlides: 5, // loop 模式下会在slides 前后复制若干个slide ，前后复制的个数不会大于原来的总个数。3就是前后各复制4个
        loopFillGroupWithBlank: true,
      },
    };
  },
  components: {
    Swiper,
    SwiperSlide,
  },
  mounted() {
    // console.log("mounted:", this.$store.state.app.walletAddress);
    // this.walletAddress = this.$store.state.app.walletAddress || "";
    // this.isRegister = this.$store.state.app.isRegister || "";

    // let query = this.$route.query
    // if (query && query.code) this.registerForm.code = query.code

    if (!/msie [6|7|8|9]/i.test(navigator.userAgent)) {
      new WOW.WOW().init();
    }
    // script.init();
    // script.animate();
    // clearInterval(timer);
  },
  computed: {
    replaceMiddleWithEllipsis() {
      return this.walletAddress.replace(/^(.{5}).*(.{5})$/, "$1...$2");
    },
  },
  methods: {
    // 跳转外部链接
    openUrl(url) {
      window.open(url);
    },
    // 复制方法
    copyText(code, type = "") {
      if (type == "code") code = `https://www.aisc.tech/#/?code=${code}`;
      // // 关键
      // navigator.clipboard
      //   .writeText(code)
      //   .then(() => {
      //     // window.alert("复制成功");
      //     // this.$message('复制成功')
      //     this.$notify({ type: "success", message: "Copy success！" });
      //   })
      //   .catch((error) => {
      //     // this.$message.warning("复制失败");
      //     // window.alert("Copy fail！", error);
      //   });

      if (document.execCommand("copy")) {
        // 创建textarea
        var textArea = document.createElement("textarea");
        textArea.value = code;
        // 使textarea不在viewport，同时设置不可见
        textArea.style.position = "fixed";
        textArea.style.opacity = 0;
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej();
          textArea.remove();
          // this.$message('复制成功')
          this.$notify({ type: "success", message: "Copy success！" });
        });
      } else if (
        navigator.clipboard &&
        typeof navigator.clipboard.writeText === "function"
      ) {
        // navigator clipboard 向剪贴板写文本
        // this.$message('复制成功')
        this.$notify({ type: "success", message: "Copy success！" });
        return navigator.clipboard.writeText(code);
      }
    },

    //锚点跳转
    goAnchor(selector) {
      /*参数selector是id选择器（#anchor14）*/
      document.querySelector(selector).scrollIntoView({
        behavior: "smooth",
      });
    },
    // 切换语言
    setLanguage() {
      this.language = this.language === "zh" ? "en" : "zh";
      this.$i18n.locale = this.language;
      localStorage.setItem("lang", this.language);
    },
    // 跳转个人页 判断地址是否注册
    goAccount() {
      if (!this.isRegister) return (this.showForm = true);
      this.$router.push({
        path: "/account",
        query: {},
      });
    },
    // 登录 判断地址是否注册过用户
    async getLogin() {
      this.$store.commit("app/UP_walletAddress", this.walletAddress);
      this.registerForm.address = this.walletAddress;
      let res = await addressLogin({ address: this.walletAddress });

      console.log("login:", res);
      // 接口判断 如果地址没绑定注册用户 就弹出信息完善框
      if (!res.code || !res.data) {
        this.$notify({
          type: "danger",
          message: this.$t("PleaseCompleteTheRegistration"),
        });
        setTimeout(() => {
          this.showForm = true;
        }, 1500);
      }
      if (res.code == 1) {
        localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo));
        localStorage.setItem("token", res.data.userinfo.token);
        this.isRegister = true;
        this.$store.commit("app/UP_Register", true);
        this.showForm = false;
      }
    },
    // okx Login
    connectOkxWallet() {
      let that = this;
      const { okxwallet, unisat } = window;
      const ua = navigator.userAgent;
      const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
      const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
      const isMobile = isIOS || isAndroid;
      const isOKApp = /OKApp/i.test(ua);
      if (isMobile && !isOKApp) {
        // 在移动设备的浏览器中打开 H5
        console.log("This is a mobile browser.");
        window.open(
          "https://okex.com/web3/connect-dapp?uri=http%3A%2F%2Fokx.xingruizhubao.com"
        );
        return;
        //okx://wallet/dapp/details?dappUrl=http%3A%2F%2Fokx.xingruizhubao.com
      } else {
        // 在其他环境中打开（例如桌面浏览器）
        console.log("This is not a mobile browser.");
      }

      try {
        if (!okxwallet) return alert("Please install okx wallet");
        localStorage.setItem("wallet", "okxwallet");
        okxwallet.bitcoin.connect().then((result) => {
          console.log("okx address:", result);
          that.walletAddress = result.address;
          // console.log(that.$store.state.app.walletAddress);
          that.showLogin = false;
          this.getLogin();
        });
        okxwallet.on("accountsChanged", (accounts) => {
          if (accounts.length > 0) {
            okxwallet.bitcoin.connect().then((result) => {
              console.log("okx address:", result);
              that.walletAddress = result.address;
              that.showLogin = false;
              that.getLogin();
            });
          }
        });
      } catch (error) {
        console.log(error);
        throw new Error("No bitcoin object.");
      }
    },

    getInterval() {
      localStorage.setItem("wallet", "walletConnect");
      timer = setInterval(async () => {
        console.log("輪詢中...");
        // const signature = await signMessage({
        //   message: "gm wagmi frens",
        // });
        // console.log('signature:', signature)

        // const balance = await fetchBalance({
        //   address: "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e",
        //   token: "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984",
        // });
        // console.log('balance:', balance)
        let accountObj = await getAccount();
        console.log("getAccount:", accountObj);
        if (accountObj && accountObj.address && accountObj.isConnected) {
          this.walletAddress = accountObj.address;
          clearInterval(timer);
          this.getLogin();
        }
        // console.log('disconnect:', await disconnect())
      }, 1000);
    },

    async connectWalletConnect() {
      this.showLogin = false;
      const modal = useWeb3Modal();
      modal.open();
      this.getInterval();

      // console.log(state)
      // console.log(events)

      // const { open, close } = useWeb3Modal()
      // modal.open({ view: 'Account' })
    },

    // logout() {
    //   this.$dialog
    //     .confirm({
    //       title: this.$t("dialogTitle"),
    //       message: this.$t("dialogMessage"),
    //       confirmButtonText: this.$t("dialogConfirmButtonText"),
    //       confirmButtonColor: "#aea2ec",
    //     })
    //     .then(() => {
    //       // window.walletAddress = ''
    //       this.walletAddress = "";
    //       localStorage.setItem("walletAddress", "");
    //       // window.parent.location.reload();
    //     })
    //     .catch(() => {
    //       // on cancel
    //     });
    // },

    submit() {
      this.$dialog
        .confirm({
          title: this.$t("dialogTitle"),
          message: this.$t("PleaseCheckYourAddress"),
          confirmButtonText: this.$t("ConfirmSubmission"),
          cancelButtonText: this.$t("cancel"),
          confirmButtonColor: "#aea2ec",
        })
        .then(async () => {
          let res = await addressRegister(this.registerForm);
          console.log("register:", res);
          if (res.code == 1) {
            localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo));
            localStorage.setItem("token", res.data.userinfo.token);
            this.isRegister = true;
            this.$store.commit("app/UP_Register", true);
            this.showForm = false;
          } else if (res.code == 0) {
            this.$notify({
              type: "danger",
              message: res.msg,
            });
          }
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>

<style lang="less" scoped>
@import "@/assets/css/slicy.css";
// @import "@/assets/css/swiper.min.css";
@import "@/assets/css/style.css";
@import "@/assets/css/new.css";
// @import "@/assets/css/slicy.css";

::v-deep .swiper {
  // margin-left: -10rem;
}
::v-deep .swiper-slide {
  width: auto !important;
}
</style>
